<template>
  <div class="h100 tableSearchListFlexPage">
    <div class="table-page-search-wrapper commonSelectWidth">
      <div style="display: flex">
        <a-row :gutter="16" style="flex: 1 0 0">
          <a-col :md="6" :sm="24">
            <service-belong-select
              :default-value="queryParams.serviceBelong"
              mode="multiple"
              @changeoption="changeoption($event, 'serviceBelong')"
            >
            </service-belong-select>
          </a-col>
          <a-col :md="6" :sm="24">
            <service-sale-cate-select
              :default-value="queryParams.serviceCategory"
              mode="multiple"
              @changeoption="changeoption($event, 'serviceCategory')"
            >
            </service-sale-cate-select>
          </a-col>
          <a-col :md="6" :sm="24">
            <service-status-select
              :default-value="queryParams.publishStatus"
              @changeoption="changeoption($event, 'publishStatus')"
            >
            </service-status-select>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-input
              v-model.trim="queryParams.serviceCode"
              :placeholder="$t('pleaseInput') + $t('serviceCode').toLowerCase()"
              @keyup.enter="refreshData"
              allowClear
            />
          </a-col>
        </a-row>
        <div class="searchBtns" style="marginleft: 12px">
          <auth-button :auth="softwarePerms.serviceConfig.view" @click="refreshData" type="info">
            <i class="iconfont icon-chazhao"></i>
            {{ $t('inquiry') }}
          </auth-button>
          <a-button @click="initiSelectValue">
            <i class="iconfont icon-qingkong"></i>
            {{ $t('clear') }}
          </a-button>
          <auth-button
            :auth="softwarePerms.serviceConfig.add"
            @click="
              () => {
                batchOperationTag = !batchOperationTag
              }
            "
          >
            <span v-if="batchOperationTag">{{ $t('cancel') }}</span>
            <span v-else>{{ $t('bulkOperations') }}</span>
          </auth-button>
        </div>
      </div>
    </div>
    <div class="tableListMain">
      <div class="dsxw-table-pagination-wrapper commonTableSty h100" ref="taskTableList">
        <div class="table-wrapper" ref="tableWrapperRef">
          <a-table
            ref="table"
            size="default"
            :components="tableComponents"
            :rowKey="(record, index) => record.serviceId"
            :pagination="false"
            :columns="columns"
            :dataSource="tbData"
            :row-selection="batchOperationTag ? rowSelection : null"
            :showHeader="!batchOperationTag"
            :loading="loadingPageData"
            :scroll="{ y: contentHeight, x: 900 }"
          >
            <!-- 批量选择时表头 -->
            <template v-if="batchOperationTag" slot="title">
              <div class="tableTitle">
                <div class="checkWarp">
                  <a-checkbox @change="allCheck" :checked="allChecked"></a-checkbox>
                </div>
                <div class="chosed">{{ `已选：${selectedRowKeys.length}` }}</div>
                <div class="operationWarp">
                  <!-- 删除 -->
                  <template v-if="selectedRowKeys.length > 0">
                    <auth-text :auth="softwarePerms.serviceConfig.delete" @click="applyReviewFun()">
                      {{ $t('applyReview') }}
                    </auth-text>
                  </template>
                  <has-no-permission-tip v-else :title="$t('pleaseSelect')" style="width: 60px">
                    <a-button class="deleteBtn" disabled>{{ $t('applyReview') }}</a-button>
                  </has-no-permission-tip>
                </div>
              </div>
            </template>
            <!-- 表格内容 -->
            <template
              slot-scope="text"
              v-for="column in columns.filter((item) => !item.special)"
              :slot="column.scopedSlots.customRender"
            >
              <table-ellipsis :text="text || '_'" :key="column.dataIndex"></table-ellipsis>
            </template>
            <template #fwgsy="text">
              <table-ellipsis :text="serviceSaleBelongFlagDictCodeObj[text] || '_'"></table-ellipsis>
            </template>
            <template #fwfl="text">
              <table-ellipsis :text="serviceSaleCateFlagDictCodeObj[text] || '_'"></table-ellipsis>
            </template>
            <template #yesNoType="text">
              <table-ellipsis :text="chooseYesNoTypeObj[text] || '_'"></table-ellipsis>
            </template>
            <template #saleState="text">
              <table-ellipsis :text="saleStateTypeObj[text] || '_'"></table-ellipsis>
            </template>
            <template #publishStatus="text">
              <a-tag v-if="servicePublishStatusDictCodeObj[text]" :color="servicePublishStateObj[text].color">
                {{ servicePublishStatusDictCodeObj[text] }}
              </a-tag>
              <span v-else>_</span>
            </template>
            <span slot="action" slot-scope="text, record" class="tableOperateSty">
              <operation-menu
                :menus="getTbRowMenus(record)"
                @clickaction="
                  (key) => {
                    doAction(key, record)
                  }
                "
              ></operation-menu>
            </span>
          </a-table>
        </div>
        <div class="pagination-wrapper">
          <a-pagination
            size="small"
            :pageSizeOptions="['20', '40', '60', '80', '100']"
            :current="pageCount"
            :pageSize="pageSize"
            :total="total"
            :totalPage="totalPage"
            :showSizeChanger="true"
            @change="changePage"
            @showSizeChange="showSizeChange"
          >
          </a-pagination>
        </div>
      </div>
    </div>
    <!-- 编辑服务 -->
    <managed-services-edit-service ref="editServiceRef" @refreshData="refreshData" :modelId="recordData.id">
    </managed-services-edit-service>
    <!-- 查看依赖 -->
    <service-Version-depend :serviceId="currentRecord.serviceId" :modelId="recordData.id" ref="versionDependRef"> </service-Version-depend>
    <!-- 编辑依赖 -->
    <managed-services-edit-depends
      ref="editDependRef"
      :serviceInfor="currentRecord"
      :modelId="recordData.id"
      :dependDetailObj="dependDetailObj"
    >
    </managed-services-edit-depends>
    <!-- 批量申请审核 -->
    <manage-service-apply-review-modal
      ref="reviewModalRef"
      :modelId="recordData.id"
      :serviceIds="selectedRowKeys"
      @afterDoAction="afterApplyAudit"
    >
    </manage-service-apply-review-modal>
    <!-- 查看审核结果 -->
    <audit-process-dialog ref="auditProcessDialogRef" :title="$t('auditProcess')" :query="auditProcessQuery">
    </audit-process-dialog>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import tableEllipsis from '@/components/Ellipsis/TableEllipsis'
import HasNoPermissionTip from '@/components/HasNoPermissionTip'
import ServiceBelongSelect from '@/views/components/ServiceBelongSelect'
import ServiceSaleCateSelect from '@/views/components/ServiceSaleCateSelect'
import ServiceStatusSelect from '@/views/components/ServiceStatusSelect'
import AuthText from '@/components/AuthText'
import AuthButton from '@/components/AuthButton'
import OperationMenu from '@/components/OperationMenu'
import ManagedServicesEditService from './ManagedServicesEditService.vue'
import ServiceVersionDepend from '@/views/components/ServiceVersionDepend.vue'
import ManagedServicesEditDepends from './ManagedServicesEditDepends.vue'
import ManageServiceApplyReviewModal from './ManageServiceApplyReviewModal'
import { minxinGetDomHeight } from '@/utils/mixin'
import { managedServicesColumns, commonServicesColumns, managedServicesRowMenus } from '../config/list'
import { softwarePerms } from '@/config/permission/index'
import tableDraggable from '@/utils/tableDraggable'
import AuditProcessDialog from '@/views/components/AuditFlowProcess/dialog.vue'
const cannotSelectTable = [-1, 3, 20, 6] // 未管理, 审核中, 已发布,已通过状态集合
export default {
  name: 'ManagedServicesList',
  mixins: [minxinGetDomHeight],
  components: {
    tableEllipsis,
    HasNoPermissionTip,
    ServiceBelongSelect,
    ServiceSaleCateSelect,
    ServiceStatusSelect,
    AuthText,
    AuthButton,
    OperationMenu,
    ManagedServicesEditService,
    ServiceVersionDepend,
    ManagedServicesEditDepends,
    ManageServiceApplyReviewModal,
    AuditProcessDialog
  },
  props: {
    recordData: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  computed: {
    ...mapState({
      instantUpdateTime: (state) => state.app.instantUpdateTime,
      servicePublishStateObj: (state) => state.dict.servicePublishStateObj
    }),
    serviceSaleBelongFlagDictCodeObj () {
      return this.$store.getters.getDictCodeObj('serviceSaleBelongFlagDictCode')
    },
    serviceSaleCateFlagDictCodeObj () {
      return this.$store.getters.getDictCodeObj('serviceSaleCateFlagDictCode')
    },
    servicePublishStatusDictCodeObj () {
      return this.$store.getters.getDictCodeObj('servicePublishStatusDictCode')
    },
    chooseYesNoTypeObj () {
      return this.$store.getters.chooseYesNoTypeObj()
    },
    saleStateTypeObj () {
      return this.$store.getters.saleStateTypeObj()
    },
    tbRowMenus () {
      return managedServicesRowMenus
    },
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange,
        getCheckboxProps: (record) => ({
          // 未管理 审核中 已发布
          props: {
            disabled: cannotSelectTable.includes(record.publishStatus)
          }
        })
      }
    }
  },
  data () {
    return {
      columns: commonServicesColumns.concat(managedServicesColumns),
      tableComponents: {},
      softwarePerms, // 权限标识
      queryParams: {},
      tbData: [],
      pageCount: 1,
      pageSize: 20,
      total: 0,
      totalPage: 1,
      selectedRowKeys: [],
      selectedRows: [],
      allChecked: false,
      batchOperationTag: false,
      wrapRef: 'tableWrapperRef',
      expectCls: '.table-wrapper .ant-table-thead',
      loadingPageData: false,
      editServiceTime: 0, // 编辑服务的时间戳
      currentRecord: {},
      dependDetailObj: {}, // 编辑依赖版本回显
      auditProcessQuery: {
        // 任务id
        instanceId: '',
        businessCode: 'service_audit'
      }
    }
  },
  created () {
    this.getPageDictData()
    this.tableComponents = tableDraggable(this.columns)
  },
  mounted () {
    // 加载页面时初始化之前的筛选值
    this.initiSelectValue()
  },
  methods: {
    // 切换筛选项
    changeoption (event, key) {
      const vm = this
      vm.$set(vm.queryParams, key, event)
    },
    // 下拉框 重置和初始化
    initiSelectValue () {
      this.queryParams = {}
      this.refreshData(true)
    },
    // 获取页面所需要的字典
    getPageDictData () {
      const dicts = [
        'getServiceSaleCateFlagDictCodeData',
        'getServiceSaleBelongFlagDictCodeData',
        'getServicePublishStatusDictCodeData'
      ]
      dicts.forEach((method) => {
        this.$store.dispatch(method)
      })
    },
    // 全选操作
    allCheck (e) {
      this.selectedRowKeys = []
      if (e.target.checked) {
        this.tbData.forEach(e=>{
          if (!cannotSelectTable.includes(e.publishStatus)) {
            this.selectedRowKeys.push(e.serviceId)
          }
        })
        this.allChecked = true
      } else {
        this.allChecked = false
      }
    },
    // 申请审核
    applyReviewFun () {
      const vm = this
      vm.$refs.reviewModalRef.visible = true
    },
    // 获取列表数据
    loadPageData () {
      const vm = this
      // 如果是全部则不传值给后端
      return new Promise((resolve, reject) => {
        const JnqueryParam = JSON.parse(JSON.stringify(vm.queryParams))
        // eslint-disable-next-line no-restricted-syntax
        for (const key in JnqueryParam) {
          if (JnqueryParam[key] === '') {
            JnqueryParam[key] = undefined
          }
        }
        JnqueryParam.modelCode = vm.recordData.code
        JnqueryParam.trimLevel = vm.recordData.trimLevel
        vm.loadingPageData = true
        vm.$api
          .getServiceByModelIn({ pageNo: vm.pageCount, pageSize: vm.pageSize, ...JnqueryParam })
          .then((res) => {
            const { data } = res
            this.tbData = data
            this.total = res.totalCount
            this.totalPage = res.totalPage
            resolve(res)
          })
          .catch((err) => {
            reject(err)
          })
          .finally(() => {
            vm.loadingPageData = false
          })
      })
    },
    // 获取操作每行的菜单
    getTbRowMenus (record) {
      return this.tbRowMenus.filter((item) => {
        return !(item.disabled && item.disabled(record))
      })
    },
    // 列表操作
    doAction (key, record) {
      const vm = this
      vm[key](record)
    },
    // 编辑服务（关联服务）
    editService (record) {
      const vm = this
      vm.$nextTick(() => {
        vm.$refs.editServiceRef.handleEdit(record)
      })
    },
    // 查看依赖
    viewDependencies (record) {
      this.currentRecord = record
      this.$refs.versionDependRef.visible = true
    },
    // 查看审核
    viewAudit (record) {
      this.auditProcessQuery.instanceId = record.instanceId
      this.$refs.auditProcessDialogRef.toggleVisible(true)
    },
    // 编辑依赖
    editDependencies (record) {
      const vm = this
      this.currentRecord = record
      vm.dependDetailObj = {}
      vm.$api
        .getVersionDependByService({
          pageSize: 100,
          pageNo: 1,
          serviceId: record.serviceId,
          modelId: this.recordData.id
        })
        .then((res) => {
          res.data.forEach((item) => {
            vm.dependDetailObj[item.ecuModuleId] = item.dependSoftwareVersion
          })
        })
        .finally(() => {
          vm.$refs.editDependRef.visible = true
        })
    },
    // 加入管理
    addManagement (record) {
      const vm = this
      const paramsData = {
        activeState: 1,
        enableState: record.enableState,
        saleState: record.saleState,
        serviceId: record.serviceId,
        modelCode: vm.recordData.code,
        modelId: vm.recordData.id,
        trimLevel: vm.recordData.trimLevel
      }
      // eslint-disable-next-line max-len
      vm.confirmModalPopup(
        { title: this.$t('addManagement'), desc: 'addManagementTip', api: 'addManagementApi' },
        paramsData
      )
    },
    // 撤回发布
    withdrawReleases (record) {
      const vm = this
      const paramsData = {
        serviceId: record.serviceId,
        modelId: vm.recordData.id,
        type: 0
      }
      // eslint-disable-next-line max-len
      vm.confirmModalPopup(
        { title: this.$t('withdrawReleases'), desc: 'withdrawReleasesTip', api: 'publishService' },
        paramsData
      )
    },
    // 发布服务
    publishService (record) {
      const vm = this
      const paramsData = {
        serviceId: record.serviceId,
        modelId: vm.recordData.id,
        type: 1
      }
      // eslint-disable-next-line max-len
      vm.confirmModalPopup(
        { title: this.$t('publish') + this.$t('service'), desc: 'publishServiceTip', api: 'publishService' },
        paramsData
      )
    },
    // 二次确认弹窗封装
    confirmModalPopup (strObj, paramsData) {
      const vm = this
      this.$confirm({
        title: strObj.title,
        content: vm.$t(strObj.desc),
        class: 'confirmStyle',
        icon: '<Icon >',
        width: 378,
        onOk () {
          vm.$api[strObj.api](paramsData).then(() => {
            vm.afterDoAction()
          })
        },
        onCancel () {}
      })
    },
    refreshData (bool = false) {
      if (bool) {
        this.pageCount = 1
      }
      this.loadPageData()
    },
    changePage (page) {
      this.pageCount = page
      this.loadPageData()
    },
    showSizeChange (current, size) {
      this.pageSize = size
      this.pageCount = 1
      this.loadPageData()
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      // 排除未管理 已发布 审核中
      const canSelectTbData = this.tbData.filter((item) => !cannotSelectTable.includes(item.publishStatus))
      if (this.selectedRowKeys.length === canSelectTbData.length) {
        this.allChecked = true
      } else {
        this.allChecked = false
      }
    },
    // 列表操作成功后
    afterDoAction () {
      const vm = this
      vm.$message.success(vm.$t('successfullyOperation'))
      vm.refreshData()
    },
    // 申请审核后初始化
    afterApplyAudit () {
      this.afterDoAction()
      this.selectedRowKeys = []
      this.selectedRows = []
      this.allChecked = false
      this.batchOperationTag = false
    }
  },
  watch: {
    instantUpdateTime: {
      handler () {
        this.selectedRowKeys = []
        this.selectedRows = []
        this.allChecked = false
        this.batchOperationTag = false
        this.refreshData(true)
      },
      immediate: true
    }
  }
}
</script>
<style lang="less" scoped>
.deleteBtn {
  font-size: 0.8rem;
  height: 26px;
  line-height: 26px;
  padding: 0;
  text-align: center;
  min-width: 58px;
}
/deep/ .operationWarp .ant-tooltip{
  width: 72px;
}
</style>
